<template>
  <div class="app-container min-h-[calc(100vh-6rem)]">
    <div
      v-if="!isInExe"
      class="text-[3rem] text-gray-500 text-center h-[calc(100vh-7rem)] flex justify-center items-center"
    >
      <span>该功能需要在客户端中使用</span>
    </div>
    <div v-else>
      <div class="flex gap-2 mb-2">
        <Geo v-model="addresses" size="mini" />

        <keywords v-model="includeKeywords" size="mini" title="搜索关键词" />

        <keywords v-model="excludeKeywords" title="排除关键词" />

        <settings v-model="setting" />
        <div class="flex-1 mx-0 my-auto">
          <el-button
            class="w-full !mb-4"
            type="primary"
            :disabled="running"
            @click="run()"
            >开始</el-button
          >

          <el-progress :percentage="progress"></el-progress>
          <!-- <div>
            运行日志
            <div></div>
          </div> -->
        </div>
      </div>

      <el-table :data="tableData">
        <el-table-column prop="name" label="名称"> </el-table-column>
        <el-table-column prop="address" label="地址"> </el-table-column>
        <el-table-column prop="website" label="网址"> </el-table-column>
        <el-table-column prop="phone" label="电话"> </el-table-column>
        <el-table-column>
          <template slot="header">
            <div class="flex flex-row-reverse">
              <el-button
                type="primary"
                plain
                size="small"
                @click="exportFile('csv')"
                >导出csv</el-button
              >
            </div>
          </template>
          <template slot-scope="scope">
            <div class="flex flex-row-reverse">
              <el-button
                type="danger"
                plain
                size="small"
                @click="remove(scope.row)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>
import Geo from './IndexComponents/geo'
import Keywords from './IndexComponents/keywords'
import Settings from './IndexComponents/settings'
import common from '@/utils/common'
export default {
  name: 'MapCollect',
  components: {
    Geo,
    Keywords,
    Settings,
  },
  data() {
    return {
      addresses: [],
      includeKeywords: [],
      excludeKeywords: [],
      setting: {},
      running: false,

      progress: 0,
      tableData: [],
      waitResponse: false,
    }
  },
  created() {
    VUE.$on('GetMerchantsResult', (json) => {
      if (typeof json === 'string') {
        console.error('客户端返回异常', json)
        this.waitResponse = false
        return
      }
      let data = json
      for (const item of data) {
        if (this.excludeKeywords.some((e) => item.Name.contains(e))) {
          continue
        }

        if (
          this.setting.setting === 'excludeMerchantWithoutContact' &&
          !item.Phone
        ) {
          continue
        }

        if (this.setting.setting === 'onlyMerchantHasPhone' && !item.Phone) {
          continue
        }

        this.tableData.push({
          name: item.Name,
          geo: item.Geo,
          address: item.Address,
          phone: item.Phone,
          website: item.Website,
        })
      }

      this.waitResponse = false
    })
  },
  destroyed() {
    VUE.$off('GetMerchantsResult')
  },
  computed: {
    isInExe() {
      return common.IsInExe()
    },
  },
  methods: {
    remove(row) {
      this.tableData = this.tableData.filter((el) => el.address !== row.address)
    },
    async run() {
      this.running = true
      if (this.addresses.length === 0) {
        this.$message.warning('请选择地区')
        return
      }

      if (this.includeKeywords.length === 0) {
        this.$message.warning('请选择关键词')
        return
      }
      const total = this.addresses.length * this.includeKeywords.length
      let step = 0
      this.progress = 0
      for (const address of this.addresses) {
        for (const keyword of this.includeKeywords) {
          this.waitResponse = true
          await new Promise((resolve) => {
            common.ExeInvoke((formProcess) => {
              const result = formProcess.GetMerchants(address, keyword)
              console.log(result)
              resolve(result)
            })
          })
          await new Promise((resolve) => {
            const timer = setInterval(() => {
              if (!this.waitResponse) {
                clearInterval(timer)
                resolve()
              }
            }, 500)
          })

          step++
          this.progress = parseInt((step * 100) / total)
        }
      }

      this.running = false
    },
    exportFile(type) {
      if (this.tableData.length === 0) {
        this.$message.warning('没有需要导出的数据')
        return
      }

      common.ExeInvoke((f) => {
        const result = f.SaveFile(JSON.stringify(this.tableData), type)

        if (!result) {
          this.$message.success('导出完成')
        } else {
          console.error('导出失败', result)
          this.$message.warning('导出失败')
        }
      })
    },
  },
}
</script>
